package com.kunsan.compose.utils

import com.kunsan.compose.BuildConfig
import java.nio.charset.StandardCharsets
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException


/**
 * 与服务端接口交换密文工具，请勿修改SLAT盐值
 * */

object DigestUtil {

    private val HEX_DIGITS = charArrayOf(
        '0', '1', '2', '3', '4', '5',
        '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
    )

    fun getRequestCheckSum(map: MutableMap<String, Any?>, exclude: String): String {
        val s = StringBuilder()
        map.entries.sortedBy { it.key }.forEach {
            if (!it.key.contains(exclude, true)) {
                s.append(it.key)
                s.append(it.value)
            }
        }
        s.append(BuildConfig.SLAT)
        return internalEncode(s.toString(), "SHA1")
    }

    // 计算并获取md5值
    fun encode32(requestBody: String): String {
        return internalEncode(requestBody, "md5").lowercase()
    }

    fun encode16(password: String): String {
        return encode32(password).substring(0, 16).lowercase()
    }

    fun encode16ByMd5(password: String): String {
        val stringBuilder = StringBuilder()
        stringBuilder.append(BuildConfig.SLAT)
        stringBuilder.append(password)
        return encode16(stringBuilder.toString())
    }

    private fun internalEncode(plaintext: String, method: String): String {
        try {
            val messageDigest = MessageDigest.getInstance(method)
            messageDigest.update(plaintext.toByteArray(StandardCharsets.UTF_8))
            return getFormattedText(messageDigest.digest())
        } catch (e: NoSuchAlgorithmException) {
        }
        return ""
    }

    /**
     * Takes the raw bytes from the digest and formats them correct.
     *
     * @param bytes
     * the raw bytes from the digest.
     * @return the formatted bytes.
     */
    private fun getFormattedText(bytes: ByteArray): String {
        val len = bytes.size
        val buf = StringBuilder(len * 2)
        // 把密文转换成十六进制的字符串形式
        for (aByte in bytes) {
            buf.append(HEX_DIGITS[aByte.toInt() shr 4 and 0x0f])
            buf.append(HEX_DIGITS[aByte.toInt() and 0x0f])
        }
        return buf.toString()
    }
}